Encapsulation refers to the practice of hiding the structure and representation of data within a class and making it accessible outside that class via accessor functions;
Or “Refers to bundling the data and methods that operate on the data into one unit the methods and data can be accessed via dot notation or accessor methods.”
Advantages of encapsulation:
Data hiding and security;
Ease of maintenance;
Ease of testing;
Speed of development;
example: Advantage: Ease of testing; By putting all the structure of the data in a single class, other classes which make use of that data can be easily tested by simply providing them with data values even before the “real” data class is available for testing;
example: Advantage: Ease of maintenance; If there are changes to the data, or how it is stored or accessed internally, only the one class needs to be changed to accommodate that. All the other classes will continue to use the public accessor methods and will not need to be changed
Inheritance:
The benefit of inheritance:
Avoids duplicate code;
Simplifies testing;
Faster development;
Can mimic real-world object relationships;
example: Avoids duplicate code; Since all functionality of the parent class is inherited, it is not necessary to duplicate the code to reproduce that functionality in the new class; Simplifies testing; Functionality inherited from a parent class does not need to be re-tested in the new class;
Advantages of encapsulation:
example:
Advantage: Ease of testing;
By putting all the structure of the data in a single class, other classes which make use of that data can be easily tested by simply providing them with data values even before the “real” data class is available for testing;
example:
Advantage: Ease of maintenance;
If there are changes to the data, or how it is stored or accessed internally, only the one class needs to be changed to accommodate that. All the other classes will continue to use the public accessor methods and will not need to be changed
Inheritance:
The benefit of inheritance:
example:
Avoids duplicate code;
Since all functionality of the parent class is inherited, it is not necessary to duplicate the code to reproduce that functionality in the new class;
Simplifies testing; Functionality inherited from a parent class does not need to be re-tested in the new class;
excellent Java course:
http://www.ntu.edu.sg/home/ehchua/programming/index.html
Tutorials:
Java Basics:
http://www.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html [Exercises]
Java OOP basics:
http://www.ntu.edu.sg/home/ehchua/programming/java/J3a_OOPBasics.html [Exercises part 1]
Java OOP Composition, Inheritance & Polymorphism:
http://www.ntu.edu.sg/home/ehchua/programming/java/j3b_oopinheritancepolymorphism.html [Exercises part 2-8]